<template>
  <div>
    <el-select v-model="selPr"
               clearable placeholder="选择省份" class="input" @change="filterMiddle">
      <el-option
          v-for="item in prs"
          :key="item"
          :value="item"
      ></el-option>
    </el-select>
    <el-input placeholder="请输入所查询生源中学的名称" class="input"
              v-model="input" clearable
              style="margin-left: 20px"
    >
    </el-input>
    <el-button @click="search" style="margin-left: 10px">查询</el-button>
    <el-button @click="reload1">重置</el-button>
    <el-button @click="open" type="primary" style="float: right;margin-top: 10px;margin-right: 10px">导入中学库</el-button>
    <el-table :data="paginationMiddle"
              tooltip-effect="dark"
              style="width: 100%;margin-left: 20px"
    class="myTable">
      <el-table-column prop="id"    label="生源中学id" v-if="false"></el-table-column>
      <el-table-column fixed prop="name"    label="生源中学名称">
      </el-table-column>
      <el-table-column prop="province"    label="生源中学所在省份"></el-table-column>
      <el-table-column prop="city"    label="所在城市">
      </el-table-column>
      <el-table-column label="总录取人数" >
        <template slot-scope="scope">
          <span v-if="middleSchools.length>0">{{getSum(scope.row.id)}}</span>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"   label="操作">
        <template slot-scope="scope">
          <el-button @click="handleOpen(scope.row.id, scope.row.name)" type="text" size="medium">查看录取详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-left: 20px"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="params.page"
                   :page-sizes="pageSizes"
                   :page-size="params.size"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="params.total"
                   v-show="yes">
    </el-pagination>

    <el-dialog
        :title=name
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">
      <el-table :data="admission"
                tooltip-effect="dark"
                style="width: 100%">
        <el-table-column fixed prop="year" label="年份"></el-table-column>
        <el-table-column fixed prop="admissionNum" label="录取人数"></el-table-column>
      </el-table>
      <div>
        <el-card class="hot-activities" style="margin-top: 20px;">
          <div style="display: flex; align-items: center;">
            <div id="myChart" style="width: 100%;height: 300px;"></div>
          </div>
        </el-card>
      </div>
      <el-button type="primary" class="my" @click="handleClose">确 定</el-button>
    </el-dialog>

    <el-dialog
        title="导入中学库"
        :visible.sync="dialogVisible1"
        width="40%"
        :before-close="handleClose">
      <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
      <el-upload
          class="upload-demo"
          action=""
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :limit=1
          accept=".xlsx,.xls"
          :auto-upload="false">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="insertExcel" style="margin-top: 10px">确定上传</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {
  getAdmission,
  getAllAdmiByUid,
  getAllByUidPage,
  getSumByUid,
  insertAdmission,
  insertMiddleSchool
} from '../../../../api/middle'
import * as XLSX from 'xlsx'
import * as echarts from 'echarts'

export function readFile (file) {
  return new Promise(resolve => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
      resolve(ev.target.result)
    }
  })
}
export async function readExcel (file, index) {
  let data = await readFile(file)
  let workbook = XLSX.read(data, {type: 'binary'})
  let worksheet = workbook.Sheets[workbook.SheetNames[index]]
  data = XLSX.utils.sheet_to_json(worksheet)
  return data
}
export default {
  inject: ['reload'],
  name: 'viewmiddle',
  data () {
    return {
      tableData: [],
      tableData1: [],
      params: {
        page: 1,
        size: 5,
        total: 100
      },
      pageSizes: [5, 8, 10, 20],
      middleSchools: [],
      middleSchool: {
        id: '',
        sum: ''
      },
      name: '',
      sum: '',
      input: '',
      dialogVisible: false,
      admission: [],
      fileTemp: {},
      file: {},
      dialogVisible1: false,
      excelList: [],
      admissionList: [],
      middleSchoolList: [],
      tableData2: [],
      yes: true,
      selPr: '',
      prs: [],
      tableData2b: [],
      lineVisible: false
    }
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.params.size = val
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.params.page = val
    },
    findAllByUidPage () {
      getAllByUidPage(this.userId, this.params.page, this.params.size).then((res) => {
        this.tableData = res.data
      })
      getAllAdmiByUid(this.userId).then((res) => {
        this.tableData2 = res // 未分页查询全部中学
        this.tableData2b = res // 备份
        this.params.total = res.length // 全部中学个数
        this.prRemove() // 调用省份去重方法
      })
    },
    getSumByUid () {
      getSumByUid(this.userId).then((res) => {
        this.middleSchools = res
      })
    },
    getSum (uid) {
      const middleSchool = this.middleSchools.find(middleSchool => middleSchool.id === uid)
      return middleSchool ? middleSchool.sum : ''
    },
    handleClose () {
      this.dialogVisible = false
      this.dialogVisible1 = false
      this.lineVisible = false
    },
    handleOpen (id, name) {
      this.dialogVisible = true
      this.name = name + '录取情况'
      getAdmission(id, this.userId).then((res) => {
        this.admission = res
        let year = []
        let number = []
        res.forEach((item) => {
          year.push(item.year)
          number.push(item.admissionNum)
        })
        this.initLine(year, number)
        if (year.length > 1) { this.lineVisible = true }
      })
    },
    search () {
      this.tableData1 = this.tableData2
      let _search = this.input.toLowerCase()
      let newListData = []
      if (_search) {
        this.tableData1.filter((item) => {
          if (
            item.name.toLowerCase().indexOf(_search) !== -1
          ) {
            newListData.push(item)
          }
        })
        this.tableData2 = newListData
        this.params.total = this.tableData2.length
      }
    },
    reload1 () {
      this.reload()
    },
    // 上传文件时处理方法
    handleChange (file, fileList) {
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') ||
            (this.fileTemp.type === 'application/vnd.ms-excel')) {
          this.loadExcel(this.fileTemp, fileList)
        } else {
          this.$message({
            type: 'error',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    // 超出最大上传文件数量时的处理方法
    handleExceed () {
      this.$message({
        type: 'warning',
        message: '超出最大上传文件数量的限制！'
      })
    },
    // 移除文件的操作方法
    handleRemove (file, fileList) {
      this.fileTemp = null
    },
    open () {
      this.dialogVisible1 = true
    },
    loadExcel (file1, fileList) {
      let data = readExcel(file1, 0)
      data.then((d) => {
        this.excelList = d
        this.changeToData(this.excelList)
      })
    },
    changeToData (jData) {
      let array1 = []
      let array2 = []
      jData.forEach((item) => {
        array1.push({id: item.school_id, name: item.name, city: item.city, province: item.province})
        array2.push({year: item.year, admissionNum: item.admission_num, schoolId: item.school_id, universityId: this.userId})
      })
      let array3 = []
      let seen = new Set()
      for (let array of array1) {
        let s = JSON.stringify(array)
        if (!seen.has(s)) {
          seen.add(s)
          array3.push(array)
        }
      }
      this.admissionList = array2
      this.middleSchoolList = array3
      console.log(this.admissionList)
    },
    insertExcel () {
      insertMiddleSchool(this.middleSchoolList)
      insertAdmission(this.admissionList)
      this.dialogVisible1 = false
      this.reload1()
    },
    filterMiddle () {
      const middles = this.tableData2b
      let filteredMiddles = middles
      if (this.selPr) {
        filteredMiddles = filteredMiddles.filter(pr => pr.province === this.selPr)
      } else {
        this.reload1()
        return
      }
      this.tableData2 = filteredMiddles
      this.params.total = this.tableData2.length
    },
    // 省份去重
    prRemove () {
      let seen = new Set()
      for (let ms of this.tableData2) {
        let s = JSON.stringify(ms.province)
        if (!seen.has(s)) {
          seen.add(s)
          this.prs.push(ms.province)
        }
      }
    },
    initLine (xTitle, xData) {
      let obj = echarts.init(document.getElementById('myChart'))
      let max = this.carryBit(Math.max(...xData))
      let option = {
        xAxis: {
          type: 'category',
          data: xTitle
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: max
        },
        series: [
          {
            data: xData,
            type: 'line'
          }
        ]
      }
      obj.setOption(option)
    },
    carryBit (x) {
      let a = (Math.floor((x / 100)) + 1) * 100
      return a
    }
  },
  computed: {
    ...mapGetters({
      userType: 'user/getUserRole',
      userAccount: 'user/getUserAccount',
      userId: 'user/getUserId'
    }),
    roleName () {
      return this.getRoleName(this.userType)
    },
    paginationMiddle () {
      const startIndex = (this.params.page - 1) * this.params.size
      const endIndex = this.params.page * this.params.size
      const tableData3 = this.tableData2.slice(startIndex, endIndex)
      return tableData3
    }
  },
  mounted () {
    this.findAllByUidPage()
    this.getSumByUid()
  }
}
</script>

<style scoped>
/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell{
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}

.my {
  margin-top: 20px;
}
.input {
  margin-top: 10px;
  margin-left: 10px;
  width: 240px;
}
.myTable {
  margin-top: 20px;
}
/deep/ .el-table__header{
  background-color: transparent;
}
.el-table th.el-table__cell{
  background-color: transparent;
}
.el-table__header{
  background-color: transparent;
}
</style>
